package com.xiaohai.big_event_system.exception;

import com.xiaohai.big_event_system.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestControllerAdvice
public class GlobalException {
    @ExceptionHandler(CustomException.class)
    public R<String> CustomException(Exception e) {
        log.info("自定义异常");
        return R.error(201, e.getMessage());
    }

    @ExceptionHandler(SQLException.class)
    public R<String> SqlException(SQLException e) {
        log.info("sql语句异常");
        return R.error(201, e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<String> handleValidationException(MethodArgumentNotValidException e) {
        Map<String, String> errors = new HashMap<>();
        e.getBindingResult().getFieldErrors().forEach(error ->
                errors.put(error.getField(), error.getDefaultMessage()));
        return R.error(201, errors.toString());
    }

    @ExceptionHandler(Exception.class)
    public R<Object> globalException(Exception e) {
        log.info("服务器内部错误");
        return R.error(201, e.getMessage());
    }
}
